import requests
from flask import Blueprint, request, jsonify
from datetime import datetime, timedelta

from extensions import db
from models import Word, WordDefinition

api = Blueprint('api', __name__)

# 第三方API地址
DICTIONARY_API_URL = "https://api.dictionaryapi.dev/api/v2/entries/en/"

@api.route('/words/lookup/<word>', methods=['GET'])
def lookup_word(word):
    try:
        # 检查本地缓存
        cached = WordDefinition.query.filter_by(word=word.lower()).first()

        # 如果缓存存在且未过期（30天）
        if cached and cached.updated_at > datetime.utcnow() - timedelta(days=30):
            return jsonify({
                'word': word,
                'phonetics': cached.get_phonetics(),  # 使用反序列化方法
                'source': 'cache'
            })

        # 调用第三方API
        response = requests.get(f"{DICTIONARY_API_URL}{word}", timeout=5)
        response.raise_for_status()
        data = response.json()

        # 提取关键信息
        phonetics = []
        for item in data:
            if 'phonetics' in item:
                phonetics.extend([
                    {
                        'text': p.get('text'),
                        'audio': p.get('audio')
                    }
                    for p in item['phonetics']
                    if p.get('text') or p.get('audio')
                ])
        print(data)
        # 保存到数据库
        if cached:
            cached.set_phonetics(phonetics)  # 使用序列化方法
        else:
            new_entry = WordDefinition(
                word=word,
            )
            new_entry.set_phonetics(phonetics)  # 使用序列化方法
            db.session.add(new_entry)

        db.session.commit()

        return jsonify({
            'word': word,
            'phonetics': phonetics,
            'source': 'api'
        })

    except Exception as e:
        print(e)
        return jsonify({
            'error': str(e),
            'message': 'Failed to fetch word data'
        }), 500


@api.route('/words', methods=['GET'])
def get_words():
    words = Word.query.all()
    return jsonify([word.to_dict() for word in words])


@api.route('/words/<int:word_id>/status', methods=['PUT'])
def update_word_status(word_id):
    data = request.get_json()
    word = Word.query.get_or_404(word_id)

    status_map = {
        'known': {
            'new': 'learning',
            'learning': 'learned',
            'learned': 'mastered',
            'mastered': 'mastered'
        },
        'unknown': {
            'new': 'new',
            'learning': 'learning',
            'learned': 'learning',
            'mastered': 'learned'
        }
    }

    new_status = status_map[data['status']][word.status]
    word.status = new_status
    word.last_reviewed = datetime.utcnow()

    db.session.commit()
    return jsonify(word.to_dict())


@api.route('/words', methods=['POST'])
def add_word():
    data = request.get_json()

    # 验证必要字段
    required_fields = ['word', 'meaning', 'type']
    if not all(field in data for field in required_fields):
        return jsonify({'error': 'Missing required fields'}), 400

    try:
        # 创建新记录
        new_word = WordDefinition(
            word=data['word'].lower().strip(),
            meaning=data['meaning'],
            type=data.get('type', 'word'),  # 默认为单词
            difficulty=data.get('difficulty', 'medium'),
            phonetic=data.get('phonetic'),
            example=data.get('example'),
            status='new',
            created_at=datetime.utcnow(),
            updated_at=datetime.utcnow()
        )

        # 处理短语/句子类型
        if data['type'] in ['phrase', 'sentence']:
            new_word.phonetics = json.dumps([])  # 短语通常不需要音标

        db.session.add(new_word)
        db.session.commit()

        return jsonify({
            'message': 'Word added successfully',
            'id': new_word.id
        }), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@api.route('/words/stats', methods=['GET'])
def get_word_stats():
    stats = {
        'total': Word.query.count(),
        'new': Word.query.filter_by(status='new').count(),
        'learning': Word.query.filter_by(status='learning').count(),
        'learned': Word.query.filter_by(status='learned').count(),
        'mastered': Word.query.filter_by(status='mastered').count(),
        'by_difficulty': {
            'easy': Word.query.filter_by(difficulty='easy').count(),
            'medium': Word.query.filter_by(difficulty='medium').count(),
            'hard': Word.query.filter_by(difficulty='hard').count()
        }
    }

    return jsonify(stats)
